package com.zahb.qadx.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.Utils;
import com.bokecc.sdk.mobile.drm.DRMServer;
import com.bokecc.sdk.mobile.util.DWSdkStorage;
import com.bokecc.sdk.mobile.util.DWStorageUtil;

import com.cretin.www.cretinautoupdatelibrary.model.TypeConfig;
import com.cretin.www.cretinautoupdatelibrary.model.UpdateConfig;
import com.cretin.www.cretinautoupdatelibrary.utils.AppUpdateUtils;
import com.cretin.www.cretinautoupdatelibrary.utils.SSLUtils;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.zahb.qadx.BuildConfig;
import com.zahb.qadx.R;
import com.zahb.qadx.buriedpoint.BuryingPointAccessibilityDelegate;
import com.zahb.qadx.appupgrade.OkHttp3Connection;
import com.zahb.qadx.appupgrade.UpdateModel;
import com.zahb.qadx.model.DataLogin;
import com.zahb.qadx.util.ActivityManager;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * Created on 2018/12/05 15:38.
 *
 * @author zhoudawei
 */
public class BaseApplication extends Application {

    static {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
            //layout.setPrimaryColorsId(R.color.colorAccent, android.R.color.white);
            return new MaterialHeader(context);
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> {
            layout.setPrimaryColorsId(R.color.colorAccent, android.R.color.white);
            return new BallPulseFooter(context);
        });
    }

    private static BaseApplication mContext;
    private DataLogin dataLogin;
    private String token;

    private DRMServer drmServer;
    private int drmServerPort;

    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks();
        initDWStorage();
        startDRMServer();

        //友盟
        UMConfigure.setLogEnabled(true);
        UMConfigure.init(this, null, "default_channel", UMConfigure.DEVICE_TYPE_PHONE, "");
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        MobclickAgent.setCatchUncaughtExceptions(!TextUtils.equals(BuildConfig.BUILD_TYPE, "debug"));
        upgrade();//升级
    }

    private void upgrade() {

        //BlankJ的初始化 跟更新库没有关系哦
        Utils.init(this);

        //如果你想使用okhttp作为下载的载体，那么你需要自己依赖okhttp，更新库不强制依赖okhttp！可以使用如下代码创建一个OkHttpClient 并在UpdateConfig中配置setCustomDownloadConnectionCreator start
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(30_000, TimeUnit.SECONDS)
                .readTimeout(30_000, TimeUnit.SECONDS)
                .writeTimeout(30_000, TimeUnit.SECONDS)
                //如果你需要信任所有的证书，可解决根证书不被信任导致无法下载的问题 start
                .sslSocketFactory(SSLUtils.createSSLSocketFactory())
                .hostnameVerifier(new SSLUtils.TrustAllHostnameVerifier())
                //如果你需要信任所有的证书，可解决根证书不被信任导致无法下载的问题 end
                .retryOnConnectionFailure(true);
        //如果你想使用okhttp作为下载的载体，那么你需要自己依赖okhttp，更新库不强制依赖okhttp！可以使用如下代码创建一个OkHttpClient 并在UpdateConfig中配置setCustomDownloadConnectionCreator end

        //更新库配置
        UpdateConfig updateConfig = new UpdateConfig()
                .setDebug(true)//是否是Debug模式
                .setBaseUrl("http://www.cretinzp.com/system/versioninfo")//当dataSourceType为DATA_SOURCE_TYPE_URL时，配置此接口用于获取更新信息
                .setMethodType(TypeConfig.METHOD_GET)//当dataSourceType为DATA_SOURCE_TYPE_URL时，设置请求的方法
                .setDataSourceType(TypeConfig.DATA_SOURCE_TYPE_URL)//设置获取更新信息的方式
                .setShowNotification(true)//配置更新的过程中是否在通知栏显示进度
                .setNotificationIconRes(R.mipmap.ic_launcher)//配置通知栏显示的图标
                .setUiThemeType(TypeConfig.UI_THEME_G)//配置UI的样式，一种有12种样式可供选择
                .setRequestHeaders(null)//当dataSourceType为DATA_SOURCE_TYPE_URL时，设置请求的请求头
                .setRequestParams(null)//当dataSourceType为DATA_SOURCE_TYPE_URL时，设置请求的请求参数
                .setAutoDownloadBackground(false)//是否需要后台静默下载，如果设置为true，则调用checkUpdate方法之后会直接下载安装，不会弹出更新页面。当你选择UI样式为TypeConfig.UI_THEME_CUSTOM，静默安装失效，您需要在自定义的Activity中自主实现静默下载，使用这种方式的时候建议setShowNotification(false)，这样基本上用户就会对下载无感知了
//                .setCustomActivityClass(CustomActivity.class)//如果你选择的UI样式为TypeConfig.UI_THEME_CUSTOM，那么你需要自定义一个Activity继承自RootActivity，并参照demo实现功能，在此处填写自定义Activity的class
                .setNeedFileMD5Check(false)//是否需要进行文件的MD5检验，如果开启需要提供文件本身正确的MD5校验码，DEMO中提供了获取文件MD5检验码的工具页面，也提供了加密工具类Md5Utils
                .setCustomDownloadConnectionCreator(new OkHttp3Connection.Creator(builder))//如果你想使用okhttp作为下载的载体，可以使用如下代码创建一个OkHttpClient，并使用demo中提供的OkHttp3Connection构建一个ConnectionCreator传入，在这里可以配置信任所有的证书，可解决根证书不被信任导致无法下载apk的问题
                .setModelClass(new UpdateModel());
        //初始化
        AppUpdateUtils.init(this, updateConfig);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        mContext = this;
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        Configuration configuration = new Configuration();
        configuration.setToDefaults();
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return resources;
    }

    public static BaseApplication getContext() {
        return mContext;
    }

    public void setDataLogin(DataLogin dataLogin) {
        this.dataLogin = dataLogin;
        if (dataLogin != null)
            this.token = dataLogin.getToken();
        else
            this.token = "";
    }

    public DataLogin getDataLogin() {
        return dataLogin;
    }

    public String getToken() {
        return token;
    }

    // 播放加密视频调用此方法
    private void initDWStorage() {
        SharedPreferences sp = getApplicationContext()
                .getSharedPreferences("myStorage", MODE_PRIVATE);
        DWSdkStorage myDWSdkStorage = new DWSdkStorage() {
            @Override
            public String get(String key) {
                return sp.getString(key, "");
            }

            @Override
            public void put(String key, String value) {
                SharedPreferences.Editor editor = sp.edit();
                editor.putString(key, value);
                editor.apply();
            }
        };
        DWStorageUtil.setDWSdkStorage(myDWSdkStorage);
    }

    // 启动DRMServer
    public void startDRMServer() {
        if (drmServer == null) {
            drmServer = new DRMServer();
            drmServer.setRequestRetryCount(20);
        }

        try {
            drmServer.start();
            setDrmServerPort(drmServer.getPort());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTerminate() {
        if (drmServer != null) {
            drmServer.stop();
        }
        super.onTerminate();
    }

    public DRMServer getDrmServer() {
        return drmServer;
    }

    public int getDrmServerPort() {
        return drmServerPort;
    }

    public void setDrmServerPort(int drmServerPort) {
        this.drmServerPort = drmServerPort;
    }

    private void registerActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                ActivityManager.getInstance().setCurrentActivity(activity);
                ViewGroup viewGroup = (ViewGroup) activity.getWindow().getDecorView().findViewById(android.R.id.content);
                mOnGlobalLayoutListener = new MOnGlobalLayoutListener(viewGroup);
                viewGroup.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                ViewGroup viewGroup = (ViewGroup) activity.getWindow().getDecorView().findViewById(android.R.id.content);
                viewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
                mOnGlobalLayoutListener = null;
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
        });
    }


    //遍历设置AccessibilityDelegate实现类
    public void setAAAAccessibilityDelegate(ViewGroup viewGroup){
        int childCount = viewGroup.getChildCount();
        for(int i=0; i<childCount; i++){
            if(viewGroup.getChildAt(i) instanceof ViewGroup){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                    if (viewGroup.getChildAt(i).hasOnClickListeners()) {
                        BuryingPointAccessibilityDelegate accessibilityDelegate = new BuryingPointAccessibilityDelegate();
                        viewGroup.getChildAt(i).setAccessibilityDelegate(accessibilityDelegate);
                    }
                }
                setAAAAccessibilityDelegate((ViewGroup) viewGroup.getChildAt(i));
            }else{
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                    if(viewGroup.getChildAt(i).hasOnClickListeners()){
                        BuryingPointAccessibilityDelegate accessibilityDelegate = new BuryingPointAccessibilityDelegate();
                        viewGroup.getChildAt(i).setAccessibilityDelegate(accessibilityDelegate);
                    }
                }
            }
        }
    }

    private class MOnGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener{
        private ViewGroup viewGroup;

        public MOnGlobalLayoutListener(ViewGroup viewGroup){
            this.viewGroup = viewGroup;
        }

        @Override
        public void onGlobalLayout() {
            setAAAAccessibilityDelegate(viewGroup);
        }
    }

    private MOnGlobalLayoutListener mOnGlobalLayoutListener;
}
